#include "strategy/strategy_factory.h"
#include "strategy/optimized_mean_reversion_strategy.h"
#include "strategy/optimized_trend_following_strategy.h"
#include "strategy/optimized_statistical_arbitrage_strategy.h"
#include <iostream>
#include <memory>
#include <vector>
#include <chrono>
#include <thread>
#include <random>

using namespace hft;

// 模拟市场数据生成器
class MarketDataSimulator {
public:
    MarketDataSimulator(const std::string& symbol, double start_price = 100.0, double volatility = 0.001)
        : symbol_(symbol), current_price_(start_price), volatility_(volatility) {
        
        // 初始化随机数生成器
        std::random_device rd;
        gen_ = std::mt19937(rd());
        dist_ = std::normal_distribution<>(0, volatility_);
    }
    
    MarketData generateNextTick() {
        // 生成随机价格变动
        current_price_ *= (1.0 + dist_(gen_));
        
        MarketData data;
        data.symbol = symbol_;
        data.timestamp = std::chrono::system_clock::now();
        data.open = current_price_ * (1.0 - volatility_);
        data.high = current_price_ * (1.0 + volatility_);
        data.low = current_price_ * (1.0 - volatility_);
        data.close = current_price_;
        data.volume = 100 + static_cast<int>(1000 * std::abs(dist_(gen_)));
        
        return data;
    }
    
private:
    std::string symbol_;
    double current_price_;
    double volatility_;
    std::mt19937 gen_;
    std::normal_distribution<> dist_;
};

// 简单的交易系统模拟器
class TradingSystemSimulator {
public:
    void registerStrategy(std::shared_ptr<Strategy> strategy) {
        strategies_.push_back(strategy);
        strategy->setTradingSystem(this);
    }
    
    void processOrder(const Order& order) {
        std::cout << "处理订单: " << order.symbol << " " 
                  << (order.direction == OrderDirection::BUY ? "买入" : "卖出")
                  << " 价格=" << order.price
                  << " 数量=" << order.quantity << std::endl;
        
        // 模拟订单执行
        // 在实际系统中，这里会与交易所API交互
    }
    
    void run(int ticks = 1000, int tick_interval_ms = 100) {
        std::cout << "启动交易系统模拟器..." << std::endl;
        
        // 创建市场数据模拟器
        MarketDataSimulator simulator1("BTC/USDT", 50000.0, 0.0005);
        MarketDataSimulator simulator2("ETH/USDT", 3000.0, 0.0008);
        
        // 启动所有策略
        for (auto& strategy : strategies_) {
            strategy->start();
            std::cout << "策略已启动: " << strategy->getName() << std::endl;
        }
        
        // 主循环
        for (int i = 0; i < ticks; ++i) {
            // 生成市场数据
            auto data1 = simulator1.generateNextTick();
            auto data2 = simulator2.generateNextTick();
            
            // 将市场数据分发给所有策略
            for (auto& strategy : strategies_) {
                strategy->onMarketData(data1);
                strategy->onMarketData(data2);
            }
            
            // 模拟时间流逝
            std::this_thread::sleep_for(std::chrono::milliseconds(tick_interval_ms));
            
            // 每100个tick输出一次状态
            if (i % 100 == 0) {
                std::cout << "已处理 " << i << " 个市场数据点" << std::endl;
            }
        }
        
        // 停止所有策略
        for (auto& strategy : strategies_) {
            strategy->stop();
            std::cout << "策略已停止: " << strategy->getName() << std::endl;
        }
        
        std::cout << "交易系统模拟器已停止" << std::endl;
    }
    
private:
    std::vector<std::shared_ptr<Strategy>> strategies_;
};

int main() {
    std::cout << "优化策略示例程序" << std::endl;
    std::cout << "=====================" << std::endl;
    
    // 创建交易系统模拟器
    TradingSystemSimulator system;
    
    // 使用工厂创建优化的策略
    auto mean_reversion = StrategyFactory::createStrategy("MeanReversion", "", true);
    auto trend_following = StrategyFactory::createStrategy("TrendFollowing", "", true);
    
    // 直接创建优化的统计套利策略（更精细的控制）
    auto stat_arb = std::make_shared<OptimizedStatisticalArbitrageStrategy>(
        "BTC/USDT", "ETH/USDT", 100, 2.0, 0.5);
    
    // 注册策略到交易系统
    system.registerStrategy(mean_reversion);
    system.registerStrategy(trend_following);
    system.registerStrategy(stat_arb);
    
    // 运行模拟
    system.run(1000, 10);  // 1000个tick，每个tick间隔10ms
    
    return 0;
}